package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 订单
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;

    //订单号 tradeNo
    @GetMapping("/tradeNo")
    public String tradeNo(HttpServletRequest request) {
        //1:UUID                   Redis
        String tradeNo = UUID.randomUUID().toString()
                .replaceAll("-", "");
        //2: MD5(userId + 时间戳)   Redis
        //3: MD5(userId)  是不需要保存的
        String userId = AuthContextHolder.getUserId(request);
        redisTemplate.opsForValue().set(userId, tradeNo);
        return tradeNo;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(String tradeNo, @RequestBody OrderInfo orderInfo,
                              HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);
        //1:校验订单号或交易号  是否正确
        if (StringUtils.isEmpty(tradeNo)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        } else {
            String no = (String) redisTemplate.opsForValue().get(userId);
            if (tradeNo.equalsIgnoreCase(no)) {
                //2:正确 直接删除
                redisTemplate.delete(userId);
            } else {
                //3:错误 返回 Result.fail().message("不能重复提交订单");
                return Result.fail().message("不能重复提交订单");
            }
        }
        //4:校验当前提交的订单中的所有商品都必须有货  (仓库项目 物流项目）
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            //判断
            boolean flag = orderInfoService.hasStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
            // 有货： 库存大于等于购买数量
            if (!flag) {
                //10款 无货  同学们一致遇到无货马上停止 马上返回进行提示 哪个商品是无款的 （单个） 批量
                return Result.fail().message(orderDetail.getSkuName() + ":缺货");
            }
        }
        //5:保存1张订单表  保存多个订单详情表   业务层
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.insertOrder(orderInfo);
        return Result.ok(orderId);
    }
    //根据ID获取订单信息
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(name = "orderId") Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    //要求拆单
    @PostMapping("/orderSplit")
    public  String  orderSplit(Long orderId,String wareSkuMap){
        //1:
        //orderId
        //wareSkuMap
        //2:保存订单   订单微服务 拆单  一个订单变成多个订单
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        //本次发消息 内容
        //[{"wareId":"1","skuIds":["9"]},{"wareId":"2","skuIds":["15"]}]
        List<Map> listMap = new ArrayList<>();
        //3：返回值  （之前已经写过了 差一个仓库ID ）  发消信 仓库那边
        for (OrderInfo orderInfo : orderInfoList) {
            Map map = orderInfoService.initWareOrder(orderInfo);
            listMap.add(map);
        }
        return JSONObject.toJSONString(listMap);

    }
}
